package com.traffic.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.traffic.api.cache.MapCacheUtils;
import com.traffic.api.entity.AlipayUser;
import com.traffic.api.service.AlipayUserService;
import com.traffic.api.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static com.traffic.api.util.GlobalUrl.*;

/**
 * Created by churcy on 2017/2/27.
 */
@Controller
public class AlipayAuthController {
    private static final Logger log = LoggerFactory.getLogger(AlipayAuthController.class);
    private MapCacheUtils cacheUtils = MapCacheUtils.getInstance();

    @Autowired
    private AlipayUserService alipayUserService;

    @ResponseBody
    @RequestMapping(value = "/cardNo")
    public Object test(HttpServletRequest request) {
        String cardNo = request.getParameter("cardNo");
        JSONObject jsonObject = new JSONObject();
        log.info("hello");
        ConcurrentHashMap concurrentHashMap = cacheUtils.getCardMap();
        if (cardNo != null) {
            jsonObject.put("initCache_map_cache", concurrentHashMap.get("CARD_NO:" + cardNo));
        } else {
            jsonObject.put("initCache_map_cache", "请输入查询的卡号");
        }
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/cardNo/check")
    public Object checkCardNo(HttpServletRequest request) {
        String cardNo = request.getParameter("cardNo");
        JSONObject jsonObject = new JSONObject();
        String originalCardNo = cardNo;
        if (cardNo != null) {
            cardNo = AlipayUtils.checkCardCache(cardNo);
            jsonObject.put("initCache_map_cache", "查询卡号为：" + originalCardNo + "  | " + "新卡号为：" + cardNo);
        } else {
            jsonObject.put("initCache_map_cache", "请输入查询的卡号");
        }
        return jsonObject;
    }

    /**
     * 获取用户信息，跳转领卡页面
     *
     * @return
     */
    @RequestMapping(value = "/alipay/user/info", method = RequestMethod.GET)
    public ModelAndView authCode() {
        log.info("用户点击授权，接口为【/alipay/user/info】");
        StringBuffer sb = new StringBuffer();
        ModelAndView modelAndView = new ModelAndView();
        try {
            sb.append(ALIPAY_AUTH + "?");
            sb.append("app_id=" + APP_ID);
            sb.append("&scope=" + AUTH_SCOPE_USER);
            sb.append("&redirect_uri=" + URLEncoder.encode(AUTH_REDIRECT_URL, UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        modelAndView.setViewName("redirect:" + sb.toString());
        return modelAndView;
    }

    /**
     * 获取用户信息跳转 消卡页面
     *
     * @return
     */
    @RequestMapping(value = "/alipay/virtualcard/page", method = RequestMethod.GET)
    public ModelAndView cardPage() {
        StringBuffer sb = new StringBuffer();
        ModelAndView modelAndView = new ModelAndView();
        try {
            sb.append(ALIPAY_AUTH + "?");
            sb.append("app_id=" + APP_ID);
            sb.append("&scope=" + AUTH_SCOPE_USER);
            sb.append("&redirect_uri=" + URLEncoder.encode(CARD_PAGE_REDIRECT_URL, UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        modelAndView.setViewName("redirect:" + sb.toString());
        return modelAndView;
    }

    @GetMapping(value = "/alipay/user/auth/info")
    @ResponseBody
    public Object userAuthForPage(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> response = new HashMap<>();
        log.info("用户同意授权，进入回调链接");
        String authCode = request.getParameter("auth_code");
        String appId = request.getParameter("app_id");
        String source = request.getParameter("source");
        String scope = request.getParameter("scope");
        log.info("请求信息为：" + "authCode: " + authCode + " appId: " + appId + " source: " + source + " scope: " + scope);
        AlipayClient alipayClient =
                new DefaultAlipayClient(ALIPAY_GATEWAY, APP_ID, APP_PRIVATE_KEY, "json", UTF_8, ALIPAY_PUBLIC_KEY, SIGN_TYPE_RSA);

        AlipaySystemOauthTokenRequest alipayRequest = new AlipaySystemOauthTokenRequest();
        alipayRequest.setCode(authCode);
        alipayRequest.setGrantType("authorization_code");

        try {
            //获取accessToken
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(alipayRequest);
            String accessToken = oauthTokenResponse.getAccessToken();
            log.info("获取accesToken：" + "accessToken:" + accessToken);
            //根据accessToken获取用户信息
            AlipayUserInfoShareRequest userInfoRequest = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse userInfoResponse = alipayClient.execute(userInfoRequest, accessToken);
            //返回数据
            String userId = userInfoResponse.getUserId();
            result.put("userId", userId);
            response = BaseResponse.setResponse(result, ResultCodeAndMessage.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            response = BaseResponse.setResponse(null, ResultCodeAndMessage.SYS_ERROR);
        }
        return response;
    }

    /**
     * 开卡回调地址
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/alipay/virtualcard/callback/page")
    public ModelAndView authToken(HttpServletRequest request) {
        log.info("用户同意授权，进入回调链接");
        ModelAndView modelAndView = new ModelAndView();

        String authCode = request.getParameter("auth_code");
        String appId = request.getParameter("app_id");
        String source = request.getParameter("source");
        String scope = request.getParameter("scope");
        log.info("请求信息为：" + "authCode: " + authCode + " appId: " + appId + " source: " + source + " scope: " + scope);
        AlipayClient alipayClient =
                new DefaultAlipayClient(ALIPAY_GATEWAY, APP_ID_AUTH, APP_PRIVATE_KEY_AUTH, "json", UTF_8, ALIPAY_PUBLIC_KEY_AUTH, SIGN_TYPE_RSA);

        AlipaySystemOauthTokenRequest alipayRequest = new AlipaySystemOauthTokenRequest();
        alipayRequest.setCode(authCode);
        alipayRequest.setGrantType("authorization_code");

        try {
            //获取accessToken
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(alipayRequest);
            String accessToken = oauthTokenResponse.getAccessToken();
            log.info("获取accesToken：" + "accessToken:" + accessToken);
            //根据accessToken获取用户信息
            AlipayUserInfoShareRequest userInfoRequest = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse userInfoResponse = alipayClient.execute(userInfoRequest, accessToken);

            //跳转到h5页面
            String userId = userInfoResponse.getUserId();
            String userName = userInfoResponse.getUserName();
            String isCertified = userInfoResponse.getIsCertified();//是否实名认证
            String certType = userInfoResponse.getCertType();//认证类型 0:身份证 1:护照 2:军官证 3:士兵证 4:回乡证 5:临时身份证 6:户口簿 7:警官证 8:台胞证 9:营业执照 10其它证件
            String province = userInfoResponse.getProvince();
            String city = userInfoResponse.getCity();
            String area = userInfoResponse.getArea();
            String address = userInfoResponse.getAddress();
            String certNo = userInfoResponse.getCertNo();
            String gender = userInfoResponse.getGender();
            String personBirthday = userInfoResponse.getPersonBirthday();
            String personCertNo = userInfoResponse.getFirmLegalPersonCertNo();
            String mobile = userInfoResponse.getMobile();
            //保存用户信息
            log.info("成功获取用户的信息：" + userId + " " + userName + " " + certNo + " " + mobile);

            do {

                //先判断是否存在
                Map<String, Object> conditions = new HashMap();
                conditions.put("userId", userId);
                AlipayUser alipayUser = new AlipayUser();
                if (StringUtils.isAnyBlank(userId)) {
                    log.info("用户信息为空：" + userId);
                    break;
                }
                List<AlipayUser> alipayUserList = alipayUserService.findByConditions(conditions);
                if (alipayUserList.size() < 1) {
                    alipayUser.setIsCertified(isCertified);
                    if (userId != null) {
                        alipayUser.setUserId(userId);
                    }
                    if (userName != null) {
                        alipayUser.setUserName(userName);
                    }
                    if (province != null) {
                        alipayUser.setProvince(province);
                    }
                    if (city != null) {
                        alipayUser.setCity(city);
                    }
                    if (area != null) {
                        alipayUser.setArea(area);
                    }
                    if (address != null) {
                        alipayUser.setAddress(address);
                    }
                    if (mobile != null) {
                        alipayUser.setMobilePhone(mobile);
                    }
                    alipayUser.setCardTime(new Date());
                    alipayUser.setCertType(certType);

                    alipayUser.setCertNo(certNo);
                    if (null != gender) {
                        //alipayUser.setGender(gender);
                    }
                    alipayUser.setBirthday(personBirthday);
                    alipayUserService.save(alipayUser);
                }
                modelAndView.setViewName("redirect:" + H5_ISUUE_CARD);
                modelAndView.addObject("userName", blurUserName(userName));
                modelAndView.addObject("userId", userId);
                modelAndView.addObject("certNo", blurCerNo(certNo));
                modelAndView.addObject("mobilePhone", mobile);
                log.info("保存用户信息成功，跳转开卡页面");
            } while (false);
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return modelAndView;
    }

    private String blurCerNo(String certNo) {
        if (certNo == null) {
            return null;
        }
        String temp = certNo.substring(1, certNo.length() - 1);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < temp.length(); i++) {
            sb.append("*");
        }
        String result = certNo.replace(temp, sb.toString());

        return result;
    }


    private String blurUserName(String userName) {
        if (userName == null) {
            return null;
        }
        String temp = userName.substring(1);
        System.out.println("*" + temp);
        String result = "*" + temp;

        return result;
    }

    /**
     * 消卡回调地址
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/alipay/revoke/virtualcard/callback/page")
    public Object revokeCard(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();

        String authCode = request.getParameter("auth_code");
        String appId = request.getParameter("app_id");
        String source = request.getParameter("source");
        String scope = request.getParameter("scope");
        System.out.println("authCode: " + authCode + " appId: " + appId + " source: " + source + " scope: " + scope);

        try {
            AlipayClient alipayClient =
                    new DefaultAlipayClient(ALIPAY_GATEWAY, APP_ID, APP_PRIVATE_KEY, "json", UTF_8, ALIPAY_PUBLIC_KEY, SIGN_TYPE_RSA2);

            AlipaySystemOauthTokenRequest alipayRequest = new AlipaySystemOauthTokenRequest();
            alipayRequest.setCode(authCode);
            alipayRequest.setGrantType("authorization_code");

            //获取accessToken
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(alipayRequest);
            String accessToken = oauthTokenResponse.getAccessToken();
            System.out.println(accessToken);

            //根据accessToken获取用户信息
            AlipayUserInfoShareRequest userInfoRequest = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse userInfoResponse = alipayClient.execute(userInfoRequest, accessToken);
            System.out.println("支付宝授权获取用户的信息为: " + JSON.toJSONString(userInfoResponse));
            String userId = userInfoResponse.getUserId();
            System.out.println("获取的userId：" + userId);
            System.out.println("获取的userName：" + userInfoResponse.getUserName());
            modelAndView.setViewName("redirect:" + H5_REVOKE_CARD);
            modelAndView.addObject("userId", userId);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return modelAndView;
    }


}
